################################################################################
# Necessary function to calculate continuation values


cvFunction = function(rnds, Cost, pEnd, p1A, p1B, deltaA, deltaB, endowA, endowB, no.negative = FALSE){
  
  VecA = seq(from = p1A, to = p1A + (rnds-1)*deltaA, by = deltaA) 
  VecB = seq(from = p1B, to = p1B + (rnds-1)*deltaB, by = deltaB)
  Rounds = c(1:rnds)
  Offerer = ifelse(Rounds%%2 == 1, "A", "B")
  Receiver = ifelse((1-Rounds%%2) == 1, "A", "B")
  
  Prob.O = ifelse(Offerer == "A", VecA, VecB) 
  Prob.R = ifelse(Receiver == "A", VecA, VecB)
  End.O = ifelse(Offerer == "A", endowA, endowB) 
  End.R = ifelse(Receiver == "A", endowA, endowB)
  
  V.O = V.R = Accept = MaxCost.O = MaxCost.R = EU.O = EU.R = Val.O = Val.R = c(rep(NA, rnds)) 
  
  EU.O[rnds] = End.O[rnds] * (1-Prob.O[rnds])
  EU.R[rnds] = End.R[rnds] * (1-Prob.R[rnds])
  
  for(ii in c(rnds:1)){
    
    EU.O[ii] = ifelse(ii < rnds, pEnd*(1-Prob.O[ii])*End.O[ii] + (1-pEnd)*V.R[ii + 1], EU.O[ii])
    EU.R[ii] = ifelse(ii < rnds, pEnd*(1-Prob.R[ii])*End.R[ii] + (1-pEnd)*V.O[ii + 1], EU.R[ii])	
    
    MaxCost.O[ii] = End.O[ii] - EU.O[ii] 
    MaxCost.R[ii] = End.R[ii] - EU.R[ii]
    
    if(no.negative == TRUE){
      Val.O[ii] =ifelse(min(MaxCost.O[ii], Cost - MaxCost.R[ii]) < 0, 0, 
                        min(MaxCost.O[ii], Cost - MaxCost.R[ii]))
    } else{
      Val.O[ii] = min(MaxCost.O[ii], Cost - MaxCost.R[ii])
    }
    
    Val.R[ii] = Cost - Val.O[ii]
    
    ifAccept = End.R[ii] - Val.R[ii]
    ifReject = EU.R[ii]
    
    Accept[ii] = round(ifAccept, 4) >= round(ifReject, 4)
    
    V.O[ii] = ifelse(Accept[ii] == TRUE, End.O[ii] - Val.O[ii], EU.O[ii])
    V.R[ii] = ifelse(Accept[ii] == TRUE, End.R[ii] - Val.R[ii], EU.R[ii])
    
    ifAccept = c()
    ifReject = c()
  }
  function.dataframe = data.frame(Rounds, Offerer, 
                                  Val.O, Val.R,
                                  EU.O, EU.R, 
                                  V.O, V.R,
                                  Accept, MaxCost.O, MaxCost.R) %>%
    mutate_at(vars(Val.O, Val.R, 
                   EU.O, EU.R, 
                   V.O, V.R, 
                   MaxCost.O, MaxCost.R), funs(round(., 2)))
  return(function.dataframe)
  
}


